package com.liao.rent.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.rent.dto.HouseOrderDto;
import com.liao.rent.dto.reqAddOrder;
import com.liao.rent.entity.*;
import com.liao.rent.mapper.HouseOrderMapper;
import com.liao.rent.service.HouseOrderService;
import com.liao.rent.service.HouseRecordService;
import com.liao.rent.service.HouseService;
import com.liao.rent.service.SysUserService;
import com.liao.rent.utils.WebSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author liao
 * @since 2024-12-06
 */
@Service
public class HouseOrderServiceImpl extends ServiceImpl<HouseOrderMapper, HouseOrder> implements HouseOrderService {

    @Autowired
    HouseService houseService;

    @Autowired
    HouseRecordService recordService;

    @Autowired
    SysUserService userService;


    @Override
    public Page<HouseOrderDto> list(int pageNum, int pageSize, HouseOrder orderParam) {
        LambdaQueryWrapper<HouseOrder> lambdaQueryWrapper = new LambdaQueryWrapper();

        if (orderParam != null) {
            Integer ownerUserId = orderParam.getOwnerUserId();
            Integer customerUserId = orderParam.getCustomerUserId();

            lambdaQueryWrapper.eq(ownerUserId != null, HouseOrder::getOwnerUserId, ownerUserId);
            lambdaQueryWrapper.eq(customerUserId != null, HouseOrder::getCustomerUserId, customerUserId);

        }

        //获取订单对象数据
        Page<HouseOrder> houseOrderPage = page(new Page<>(pageNum, pageSize),lambdaQueryWrapper);
        Page<HouseOrderDto> houseOrderDtoPage = new Page<>();

        //获取对象数组
        List<HouseOrder> orderList = houseOrderPage.getRecords();
//        使用stream流进行转换
        List<HouseOrderDto> orderDtoList = orderList.stream().map(order -> {
            HouseOrderDto houseOrderDto = new HouseOrderDto();
            houseOrderDto.setHouseOrder(order);
//            获取房源id
            Integer houseId = order.getHouseId();
            //            根据房源id获取房源对象
            House house = houseService.getById(houseId);
//            对dto中的数组赋值
            houseOrderDto.setTitle(house.getTitle());
            houseOrderDto.setAddress(house.getAddress());
            houseOrderDto.setMonthPrice(house.getMonthPrice());
            houseOrderDto.setHouseType(Integer.valueOf(house.getHouseType()));
            houseOrderDto.setBanner_urls(house.getBannerUrl());
            //获取房源入住记录表id
            Integer recordId = house.getRecordId();
            HouseRecord record = recordService.getById(recordId);
            houseOrderDto.setStartTime(record.getLastStartTime());
            houseOrderDto.setEndTime(record.getLastEndTime());
            //获取租客和房主用户信息
            SysUser customerUser = userService.getById(order.getCustomerUserId());
            SysUser ownerUser = userService.getById(order.getOwnerUserId());
            houseOrderDto.setCustomerUserName(customerUser.getUserName());
            houseOrderDto.setOwnerUserName(ownerUser.getUserName());
            houseOrderDto.setCustomerUserPhone(customerUser.getPhone());
            houseOrderDto.setOwnerUserrPhone(ownerUser.getPhone());

            return houseOrderDto;

        }).toList();


        //设置总数
        houseOrderDtoPage.setTotal(houseOrderPage.getTotal());
//        设置总页码
        houseOrderDtoPage.setPages(houseOrderPage.getPages());
        houseOrderDtoPage.setRecords(orderDtoList);

        return houseOrderDtoPage;
    }

    @Override
    public Boolean add(reqAddOrder requestAddOrder) {


    LocalDate startDate = requestAddOrder.getStartDate();
    if (startDate.isBefore(LocalDate.now()) ){
        throw new RuntimeException("入住日期不能早于当前日期");
    }

    //获取当前对象
        SysUserDetails user = WebSecurityUtils.getUser();

//获取当前房源数据
        House house = houseService.getById(requestAddOrder.getHouseId());


            if( house.getStatus() == 3){
                throw new RuntimeException("该房源已出租");
            }


        HouseOrder houseOrder = new HouseOrder();
        houseOrder.setCustomerUserId(user.getUser().getId());
//        设置房东信息
        houseOrder.setOwnerUserId(house.getUserId());
        houseOrder.setHouseId(requestAddOrder.getHouseId());
        //订单状态（1.生效中，2.申请退租，3.已退租，4已过期）
        houseOrder.setStatus("1");
        houseOrder.setOrderId(requestAddOrder.getHouseId());
        houseOrder.setMonthPrice(house.getMonthPrice());
//计算日期差
        long days = requestAddOrder.getStartDate().until(requestAddOrder.getEndDate(), ChronoUnit.DAYS);
        houseOrder.setDayNum((int)days);
//计算总金额
    BigDecimal multiply = house.getMonthPrice().divide(new BigDecimal(30), BigDecimal.ROUND_CEILING).multiply(new BigDecimal(days));
    int i = multiply.intValue();
    BigDecimal bigDecimal = new BigDecimal(i);
    houseOrder.setTotalAmount(bigDecimal);


        // 需要存数据到房源记录表中
        HouseRecord houseRecord = new HouseRecord();
        houseRecord.setHouseId(requestAddOrder.getHouseId());
        houseRecord.setContactName(user.getUser().getUserName());
        houseRecord.setContactPhone(user.getUser().getPhone());
        houseRecord.setLastStartTime(requestAddOrder.getStartDate().atStartOfDay());
        houseRecord.setLastEndTime(requestAddOrder.getEndDate().atStartOfDay());

        //修改房源状态
        LambdaUpdateWrapper<House> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(House::getHouseId, requestAddOrder.getHouseId());
//        设置房源状态为已经租出
        lambdaUpdateWrapper.set(House::getStatus, "3");


    recordService.save(houseRecord);

    lambdaUpdateWrapper.set(House::getRecordId,houseRecord.getRecordId());
        houseService.update(lambdaUpdateWrapper);




        save(houseOrder);

        return true;

    }


    /**
     * 订单状态定时更新任务 定时更新方法
     */
    public void updateOrderStatusScheduled() {
        // 查询所有状态为1（生效中）的订单
        List<HouseOrder> orders = list(new LambdaQueryWrapper<HouseOrder>().eq(HouseOrder::getStatus, "1"));
        for (HouseOrder order : orders) {

            Integer houseId = order.getHouseId();
            House house = houseService.getById(houseId);
            Integer recordId = house.getRecordId();
            HouseRecord houseRecord = recordService.getById(recordId);

            // 判断订单是否已经过期
            if (houseRecord.getLastEndTime().isBefore(LocalDateTime.now())) {
                // 更新订单状态为4（已过期）
                order.setStatus("4");
                updateById(order);
            }
        }
    }
}
